//
//  ViewController.swift
//  GridViewExample
//
//  Created by Kyohei Ito on 2016/10/30.
//  Copyright © 2016年 Kyohei Ito. All rights reserved.
//

import UIKit
import GridView

extension UIColor {
    fileprivate convenience init(hex: Int, alpha: CGFloat = 1) {
        let red = CGFloat((hex & 0xFF0000) >> 16) / 255
        let green = CGFloat((hex & 0x00FF00) >> 8 ) / 255
        let blue = CGFloat((hex & 0x0000FF) >> 0 ) / 255
        
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
}

class TimeTableViewController: UIViewController {
    @IBOutlet weak var timeTableView: GridView!
    @IBOutlet weak var channelListView: GridView!
    @IBOutlet weak var dateTimeView: GridView!

    private let channels: [String] = ["News", "Anime", "Drama", "MTV", "Music", "Pets", "Documentary", "Soccer", "Cooking", "Gourmet", "Extreme", "Esports"]
    public var channel_width: [Int] = [60,60,80,60,30,40,120,80,80,70,60,100]
    fileprivate lazy var slotList: [[Slot]] = {
        let detailText = "TestData"
        let minutesOfDay = 24 * 60
        let frames = [10]
        return self.channels.enumerated().map { index, channel in
            var slots: [Slot] = []
            var totalMinutes = 0
            while totalMinutes < minutesOfDay {
                var minutes = frames[Int(arc4random_uniform(UInt32(frames.count)))]
                let startAt = totalMinutes + minutes
                minutes -= max(startAt - minutesOfDay, 0)
                let slot = Slot(minutes: minutes, startAt: totalMinutes, title: "\(channel)'s slot", detail: detailText)
                totalMinutes = startAt
                slots.append(slot)
            }
            return slots
        }
    }()
    
    private lazy var channelListDataSource: ChannelListDataSource = .init(channels: self.channels,widths: self.channel_width,view: self)
    private let dateTimeDataSource = DateTimeGridViewDataSource()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        view.backgroundColor = .black
        view.layoutIfNeeded()
        
        timeTableView.register(TimeTableGridViewCell.nib, forCellWithReuseIdentifier: "TimeTableGridViewCell")
        channelListView.register(ChannelListGridViewCell.nib, forCellWithReuseIdentifier: "ChannelListGridViewCell")
        dateTimeView.register(DateTimeGridViewCell.nib, forCellWithReuseIdentifier: "DateTimeGridViewCell")
//        self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
//        timeTableView.layoutWithoutFillForCell = true
//        self.automaticallyAdjustsScrollViewInsets = true
        timeTableView.superview?.clipsToBounds = true
//        timeTableView.contentInset.top = channelListView.bounds.height
        timeTableView.minimumScale = Scale(x: 1.0, y: 1.0)
        timeTableView.maximumScale = Scale(x: 2.0, y: 2.0)
//        timeTableView.scrollIndicatorInsets.top = timeTableView.contentInset.top
//        timeTableView.scrollIndicatorInsets.left = dateTimeView.bounds.width
        timeTableView.dataSource = self
        timeTableView.delegate = self
        timeTableView.reloadData()
        
//        channelListView.layoutWithoutFillForCell = true
        channelListView.superview?.backgroundColor = UIColor(hex: 0xF1F1F1)
        channelListView.superview?.isUserInteractionEnabled = true
        channelListView.minimumScale.x = timeTableView.minimumScale.x
        channelListView.maximumScale.x = timeTableView.maximumScale.x
        channelListView.dataSource = channelListDataSource
        channelListView.delegate = channelListDataSource
        channelListView.reloadData()
        
        dateTimeView.superview?.clipsToBounds = true
        dateTimeView.superview?.backgroundColor = UIColor(hex: 0xF1F1F1)
        dateTimeView.superview?.isUserInteractionEnabled = true
        dateTimeView.contentInset.top = channelListView.bounds.height
        dateTimeView.minimumScale.y = timeTableView.minimumScale.y
        dateTimeView.maximumScale.y = timeTableView.maximumScale.y
        dateTimeView.isInfinitable = false
        dateTimeView.dataSource = dateTimeDataSource
        dateTimeView.delegate = dateTimeDataSource
        dateTimeView.reloadData()
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        
        coordinator.animate(alongsideTransition: { _ in
            self.timeTableView.invalidateContentSize()
            self.channelListView.invalidateContentSize()
            self.view.layoutIfNeeded()
        })
    }
}

extension TimeTableViewController: GridViewDataSource, GridViewDelegate {
    func numberOfColumns(in gridView: GridView) -> Int {
        return slotList.count
    }
    
    func gridView(_ gridView: GridView, numberOfRowsInColumn column: Int) -> Int {
        return slotList[column].count
    }
    
    func gridView(_ gridView: GridView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(slotList[indexPath.column][indexPath.row].minutes * 2)
    }
    
    func gridView(_ gridView: GridView, cellForRowAt indexPath: IndexPath) -> GridViewCell {
        let cell = gridView.dequeueReusableCell(withReuseIdentifier: "TimeTableGridViewCell", for: indexPath)
        if let cell = cell as? TimeTableGridViewCell {
            cell.configure(slotList[indexPath.column][indexPath.row])
        }
        
        return cell
    }
    
    func gridView(_ gridView: GridView, didScaleAt scale: CGFloat) {
        channelListView.contentScale(scale)
        dateTimeView.contentScale(scale)
    }
    
    func gridView(_ gridView: GridView, didSelectRowAt indexPath: IndexPath) {
        gridView.deselectRow(at: indexPath)
//        gridView.scrollToRow(at: indexPath, at: [.topFit, .centeredHorizontally], animated: true)
        NSLog("%ld%ld", indexPath.column,indexPath.row)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        if scrollView.contentOffset.y < 0 {
//            scrollView.contentOffset.y = 0
//        }
        channelListView.contentOffset.x = scrollView.contentOffset.x
        dateTimeView.contentOffset.y = scrollView.contentOffset.y
        NSLog("%lf",scrollView.contentOffset.x)
    }
    
    func gridView(_ gridView: GridView, widthForColumn column: Int) -> CGFloat {
        return CGFloat(channel_width[column])
    }
}

final class DateTimeGridViewDataSource: NSObject, GridViewDataSource, GridViewDelegate {
    func gridView(_ gridView: GridView, numberOfRowsInColumn column: Int) -> Int {
        return 128
    }
    
    func gridView(_ gridView: GridView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10 * 2
    }
    
    func gridView(_ gridView: GridView, cellForRowAt indexPath: IndexPath) -> GridViewCell {
        let cell = gridView.dequeueReusableCell(withReuseIdentifier: "DateTimeGridViewCell", for: indexPath)
        if let cell = cell as? DateTimeGridViewCell {
            cell.configure(indexPath.row)
        }
        
        return cell
    }
    
    func gridView(_ gridView: GridView, didSelectRowAt indexPath: IndexPath) {
        //        gridView.deselectRow(at: indexPath)
        //        gridView.scrollToRow(at: indexPath, at: [.topFit, .centeredHorizontally], animated: true)
        NSLog("%ld%ld", indexPath.column,indexPath.row)
    }
}

final class ChannelListDataSource: NSObject, GridViewDataSource, GridViewDelegate {
    let channels: [String]
    var widths: [Int]
    var timeGrdiView: TimeTableViewController
    var origin_width: [Int]
    
    init(channels: [String],widths: [Int],view: TimeTableViewController) {
        self.channels = channels
        self.widths = widths
        self.timeGrdiView = view
        self.origin_width = widths
    }
    
    func numberOfColumns(in gridView: GridView) -> Int {
        return channels.count
    }
    
    func gridView(_ gridView: GridView, numberOfRowsInColumn column: Int) -> Int {
        return 1
    }
    
    func gridView(_ gridView: GridView, cellForRowAt indexPath: IndexPath) -> GridViewCell {
        let cell = gridView.dequeueReusableCell(withReuseIdentifier: "ChannelListGridViewCell", for: indexPath)
        if let cell = cell as? ChannelListGridViewCell {
            cell.configure(channels[indexPath.column],id: indexPath.column)
            cell.moveCallBack = { (_ selectIndex:Int,_ width :CGFloat)->Void in
                self.widths[indexPath.column] = Int(width)
                self.timeGrdiView.channel_width[indexPath.column] = Int(width)
                gridView.reloadData()
                self.timeGrdiView.timeTableView.reloadData()
                self.timeGrdiView.timeTableView.contentOffset.x = gridView.contentOffset.x
                
//                gridView.updateConstraints()
            }
        }
        
        return cell
    }
    
    func gridView(_ gridView: GridView, didSelectRowAt indexPath: IndexPath) {
//        gridView.deselectRow(at: indexPath)
        //        gridView.scrollToRow(at: indexPath, at: [.topFit, .centeredHorizontally], animated: true)
        NSLog("%ld%ld", indexPath.column,indexPath.row)
//        self.widths[indexPath.column] += 10
//        self.timeGrdiView.channel_width[indexPath.column] += 10
//        gridView.reloadData()
//        self.timeGrdiView.timeTableView.reloadData()
        
    }
    
    func gridView(_ gridView: GridView, widthForColumn column: Int) -> CGFloat {
        return CGFloat(widths[column])
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.timeGrdiView.timeTableView.contentOffset.x = scrollView.contentOffset.x
    }
}
